package com.stox.repository.file;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import com.stox.model.Country;
import com.stox.repository.CountryRepository;

@Component
public class CountryFileRepository 
			extends AbstractFileRepository<Country, Void> 
			implements CountryRepository, InitializingBean {

	private final List<Country> countries = new ArrayList<Country>();
	
	public void afterPropertiesSet() throws Exception {
		super.createPartition(null);
		iterate(new EntityIterator<Country>(){
			public boolean shouldContinue(Country country) {
				countries.add(country);
				return true;
			}
		}, null);
	}
	
	@Override
	protected Country deserialize(String text, Void partitionModel) {
		return new Country(text);
	}

	@Override
	protected String serialize(Country country) {
		return country.toString();
	}

	@Override
	protected String getFilePath(Void partitionModel) {
		return getFilebasePath() + File.separator + "country.csv";
	}

	public List<Country> findAll(){
		return countries;
	}
	
	public Country save(Country country) {
		if(!countries.contains(country)){
			countries.add(country);
			return super.save(country, null);
		}
		return country;
	}
	
}
